/**
 * Notes: 设备模块控制器
 * Date: 2025-01-27
 */

const BaseController = require('./base_controller.js');
const DeviceService = require('../service/device_service.js');
const timeUtil = require('../../framework/utils/time_util.js');
const dataCheck = require('../../framework/validate/data_check.js');

class DeviceController extends BaseController {

	/**
	 * 获取门店设备列表
	 */
	async getDeviceList() {
		let rules = {
			storeId: 'string|must|comment=门店ID'
		};

		// 数据校验
		let input = this.validateData(rules);

		let service = new DeviceService();
		return await service.getDeviceList(input.storeId);
	}

	/**
	 * 获取设备详情
	 */
	async getDeviceDetail() {
		let rules = {
			deviceId: 'string|must|comment=设备ID'
		};

		// 数据校验
		let input = this.validateData(rules);

		let service = new DeviceService();
		return await service.getDeviceDetail(input.deviceId);
	}

	/**
	 * 控制设备开关
	 */
	async controlDevice() {
		this.ensureAuthenticatedForWrite();
		let route = this._route || '';
		let defaultAction = '';
		if (route === 'device/on') defaultAction = 'on';
		if (route === 'device/off') defaultAction = 'off';

		let rules = {
			deviceId: 'string|false|comment=设备ID',
			action: 'string|false|comment=操作类型(on/off)',
			duration: 'int|false|comment=使用时长(分钟)',
			options: 'object|false|comment=额外选项'
		};

		// 数据校验
		let input = this.validateData(rules);
		if (!input.action && defaultAction) input.action = defaultAction;

		// 权限检查：对于关闭设备操作，需要检查用户权限
		// 判断是否为管理员请求：检查调用来源是否为merchant
		// 如果是普通用户关闭设备，需要检查权限
		const isAdminRequest = this._request._callFrom === 'merchant';
		
		if (input.action === 'off' && !isAdminRequest) {
			const deviceStatusManager = require('../service/device_status_manager.js');
			const currentUserId = this._userId;
			
			const hasPermission = await deviceStatusManager.checkDevicePermission(input.deviceId, currentUserId);
			if (!hasPermission.hasPermission) {
				throw new Error(hasPermission.message || '该设备正在使用中，无法操作');
			}
		}

		// 处理options参数
		const options = input.options || {};

		let service = new DeviceService();
		return await service.controlDevice(input.deviceId, input.action, input.duration, options);
	}

	/**
	 * 更新设备状态
	 */
	async updateDeviceStatus() {
		this.ensureAuthenticatedForWrite();
		let rules = {
			deviceId: 'string|must|comment=设备ID',
			status: 'int|must|comment=设备状态'
		};

		// 数据校验
		let input = this.validateData(rules);

		let service = new DeviceService();
		return await service.updateDeviceStatus(input.deviceId, input.status);
	}

	/**
	 * 获取设备实时状态
	 */
	async getDeviceRealTimeStatus() {
		let rules = {
			deviceId: 'string|must|comment=设备ID'
		};

		// 数据校验
		let input = this.validateData(rules);

		let service = new DeviceService();
		return await service.getDeviceRealTimeStatus(input.deviceId);
	}

	/**
	 * 获取门店设备实时状态
	 */
	async getStoreDevicesRealTimeStatus() {
		let rules = {
			storeId: 'string|must|comment=门店ID'
		};

		// 数据校验
		let input = this.validateData(rules);

		let service = new DeviceService();
		const deviceStatuses = await service.getStoreDevicesRealTimeStatus(input.storeId);

		// 直接返回数据，不需要包装，因为框架会自动处理
		return deviceStatuses;
	}

	/**
	 * 获取设备状态监控摘要
	 */
	async getDeviceStatusSummary() {
		try {
			const DeviceStatusMonitor = require('../service/device_status_monitor.js');
			const monitor = new DeviceStatusMonitor();
			
			// 获取设备状态摘要
			const summary = monitor.getDeviceStatusSummary();
			
			return {
				success: true,
				message: '设备状态监控摘要获取成功',
				data: summary,
				timestamp: timeUtil.time()
			};
		} catch (error) {
			console.error('获取设备状态监控摘要失败:', error);
			return {
				success: false,
				message: '获取设备状态监控摘要失败',
				error: error.message
			};
		}
	}

	/**
	 * 获取离线设备列表
	 */
	async getOfflineDevices() {
		try {
			const DeviceStatusMonitor = require('../service/device_status_monitor.js');
			const monitor = new DeviceStatusMonitor();
			
			// 获取离线设备列表
			const offlineDevices = monitor.getOfflineDevices();
			
			return {
				success: true,
				message: '离线设备列表获取成功',
				data: offlineDevices,
				count: offlineDevices.length,
				timestamp: timeUtil.time()
			};
		} catch (error) {
			console.error('获取离线设备列表失败:', error);
			return {
				success: false,
				message: '获取离线设备列表失败',
				error: error.message
			};
		}
	}

	/**
	 * 获取设备故障历史
	 */
	async getDeviceFaultHistory() {
		let rules = {
			deviceId: 'string|false|comment=设备ID（可选）',
			limit: 'int|false|comment=返回数量限制'
		};

		// 数据校验
		let input = this.validateData(rules);

		try {
			const SimpleFaultHandler = require('../service/simple_fault_handler.js');
			const faultHandler = new SimpleFaultHandler();
			
			// 获取故障历史
			const faultHistory = faultHandler.getFaultHistory(input.deviceId, input.limit || 50);
			
			return {
				success: true,
				message: '设备故障历史获取成功',
				data: faultHistory,
				count: faultHistory.length,
				timestamp: timeUtil.time()
			};
		} catch (error) {
			console.error('获取设备故障历史失败:', error);
			return {
				success: false,
				message: '获取设备故障历史失败',
				error: error.message
			};
		}
	}

	/**
	 * 手动触发设备故障处理
	 */
	async triggerDeviceFaultHandling() {
		this.ensureAuthenticatedForWrite();
		
		let rules = {
			deviceId: 'string|must|comment=设备ID',
			faultType: 'string|must|comment=故障类型',
			faultMessage: 'string|false|comment=故障信息'
		};

		// 数据校验
		let input = this.validateData(rules);

		try {
			const SimpleFaultHandler = require('../service/simple_fault_handler.js');
			const faultHandler = new SimpleFaultHandler();
			
			// 触发故障处理
			const result = await faultHandler.handleDeviceFault(
				input.deviceId, 
				input.faultType, 
				input.faultMessage || '手动触发故障处理'
			);
			
			return {
				success: true,
				message: '设备故障处理已触发',
				data: result,
				timestamp: timeUtil.time()
			};
		} catch (error) {
			console.error('触发设备故障处理失败:', error);
			return {
				success: false,
				message: '触发设备故障处理失败',
				error: error.message
			};
		}
	}
}

module.exports = DeviceController;